/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

package com.bullionxpress.server.impl;

import java.rmi.RemoteException;
import com.bullionxpress.shared.service.DuplicateBullionIDException;
import com.bullionxpress.shared.service.BullionNotFoundException;
import com.bullionxpress.shared.service.InvalidBullionIDFormatException;
import com.bullionxpress.shared.service.BullionDatabase;
import com.bullionxpress.shared.model.Bullion;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;


public class BullionManager extends java.rmi.server.UnicastRemoteObject implements BullionDatabase {

    public BullionManager() throws RemoteException {
        //What should go in the constructor?
    }
    Connection conn = null;
    Statement statement = null;

    public void connect() {

        try {
            conn = DatabaseManager.getConnection();

            try {
                statement = conn.createStatement();
                statement.executeUpdate("CREATE TABLE IF NOT EXISTS bullion (owner varchar(256), id varchar(256), price double, title varchar(256))");
            } catch (Exception ex) {
                System.out.println(ex);
                ex.printStackTrace();
            }

        } catch (Exception ex) {
            System.out.println(ex);
            ex.printStackTrace();
        }
    }

    public Bullion[] getAll() {

        try {

            String query = "SELECT * FROM bullion";
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            ResultSet result = statement.executeQuery(query);
            Vector v = new Vector();
            while (result.next()) {
                Bullion bullion = get(result.getString("id"));
                v.addElement(bullion);
            }
            Bullion[] bullionList = new Bullion[v.size()];
            for (int i = 0; i < v.size(); i++) {
                bullionList[i] = (Bullion) v.get(i);
            }
            return bullionList;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public Bullion get(String id) throws BullionNotFoundException {
        if (id == null) {
            throw new IllegalArgumentException();
        }
        String query = "SELECT * FROM bullion WHERE id = '" + id + "'";
        ResultSet result = null;
        boolean r = false;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            result = statement.executeQuery(query);
            r = result.next();
        } catch (Exception ex) {
        }

        if (r) {
            Bullion bullion = new Bullion();
            try {
                bullion.setOwner(result.getString("owner"));
                bullion.setId(result.getString("id"));
                bullion.setPrice(result.getDouble("price"));
                bullion.setTitle(result.getString("title"));
            } catch(Exception ex){
                throw new BullionNotFoundException();
            }
            return bullion;
        } else {
            throw new BullionNotFoundException();
        }
    }

    public void add(Bullion b) throws DuplicateBullionIDException, InvalidBullionIDFormatException {

        if (b == null) {
            throw new IllegalArgumentException();
        } else if (b.getId() == null) {
            throw new InvalidBullionIDFormatException();
        } else if (b.getId().length() != 13) {
            throw new InvalidBullionIDFormatException();
        }

        try {
            Bullion a = get(b.getId());
            throw new DuplicateBullionIDException();
        } catch(BullionNotFoundException ex){
            
        }

        String query = "INSERT INTO bullion (owner, id, title, price)  VALUES ( '" + b.getOwner() + "', '" + b.getId() + "', '" + b.getTitle() + "', " + b.getPrice() + ")";
        int n = 0;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            n = statement.executeUpdate(query);
        } catch (SQLException ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }
        //System.out.println("INSERT " + n);
        if (n != 1) {
            throw new DuplicateBullionIDException();
        }
    }

    public void delete(String id) throws BullionNotFoundException, InvalidBullionIDFormatException {

        if (id == null) {
            throw new IllegalArgumentException();
        } if( id.length() != 13 ){
            throw new InvalidBullionIDFormatException();
        }

        String sql = "DELETE FROM bullion WHERE id = '" + id + "'";

        int n = 0;
        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            n = statement.executeUpdate(sql);
            System.out.println("DELETE:" + n);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        if (n < 1) {
            throw new BullionNotFoundException();
        }

    }

    public Bullion[] getAllBullionByAccount(String owner) throws BullionNotFoundException {
        if (owner == null) {
            throw new IllegalArgumentException();
        }

        String query = "SELECT * FROM bullion WHERE owner = '" + owner + "'";
        ResultSet result = null;

        try {
            conn = DatabaseManager.getConnection();
            statement = conn.createStatement();
            System.out.println(query);
            result = statement.executeQuery(query);
        } catch (Exception ex) {
        }

        Vector v = new Vector();

        int c = 0;
        try {
            while (result.next()) {
                Bullion bullion = new Bullion();
                bullion.setOwner(result.getString("owner"));
                bullion.setId(result.getString("id"));
                bullion.setPrice(result.getDouble("price"));
                bullion.setTitle(result.getString("title"));
                v.addElement(bullion);
                c++;
            }
        } catch (Exception ex) {
            throw new BullionNotFoundException();
        }

        if (c == 0) {
            throw new BullionNotFoundException();
        }

        Bullion[] bullionList = new Bullion[v.size()];
        for (int i = 0; i < v.size(); i++) {
            bullionList[i] = (Bullion) v.get(i);
        }

        return bullionList;

    }

    public void close() {
        //try {
        //    conn.close();
        //} catch (SQLException ex) {
        //    ex.printStackTrace();
        //}
    }

    public int count() {
        int r = 0;
        Bullion[] b = getAll();
        return b.length;
    }

   

}
